package app;

import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.example.menhoo.toollibrary.common.assist.Check;
import com.example.menhoo.toollibrary.common.helper.MessageUtil;
import com.example.menhoo.toollibrary.common.utils.AndroidUtil;
import com.example.menhoo.toollibrary.common.utils.BitmapUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.lidroid.xutils.util.LogUtils;
import com.rey.material.widget.ProgressView;
import com.socks.library.KLog;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import application.AppApplication;
import application.HttpUrlConstant;
import application.KeyConstant;
import application.UIApplication;
import interfaces.IDownLoadListener;
import interfaces.IReturnObject;
import mainUI.AppActivity;
import menhoo.com.i8officelibrary.R;
import receiver.DownloadErrorReceiver;
import receiver.DownloadFinishReceiver;
import receiver.DownloadLoadingReceiver;
import receiver.DownloadStartReceiver;
import tools.ToastUtil;
import utils.FileUtils;

/**
 * 更新app页面
 * Created by yanglei on 15/11/1.
 */

public class UploadApp extends AppActivity {
    public static String Tag = "UploadApp";


    String VERSION = null;
    String URL = null;
    String VERSION_INFO = null;

    TextView textViewVer;

    TextView textViewCurrVerIsNew;

    TextView textViewProgress;

    ProgressView progress;

    Button button;

    LinearLayout linearLayoutVersion;

    FrameLayout frameLayoutUploading;

    ImageView titlebar_btn_back;

    TextView AppDesc;

    ImageView AppIconBackground;

    ImageView AppIconTitle;
    String path;
    protected Map<String, HttpHandler> downloadList = new HashMap<String, HttpHandler>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
//        setLoadingView(R.layout.loading_round);

        super.onCreate(savedInstanceState);
        //
        setContentView(R.layout.upload_app);
        setStatusBarVisible(View.GONE);
        try {
            textViewVer = (TextView) findViewById(R.id.textViewVer);
            textViewCurrVerIsNew = (TextView) findViewById(R.id.textViewCurrVerIsNew);
            textViewProgress = (TextView) findViewById(R.id.textViewProgress);
            progress = (ProgressView) findViewById(R.id.progress);
            button = (Button) findViewById(R.id.button);
            linearLayoutVersion = (LinearLayout) findViewById(R.id.linearLayoutVersion);
            frameLayoutUploading = (FrameLayout) findViewById(R.id.frameLayoutUploading);
            titlebar_btn_back = (ImageView) findViewById(R.id.titlebar_btn_back);
            AppDesc = (TextView) findViewById(R.id.AppDesc);
            AppIconBackground = (ImageView) findViewById(R.id.AppIconBackground);
            AppIconTitle = (ImageView) findViewById(R.id.AppIconTitle);

            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    getData();
                }
            });

            titlebar_btn_back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });


        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }

        String version = AndroidUtil.getVerName(this);
        textViewVer.setText(version);
        try {
            VERSION = getIntent().getExtras().getString("version");
            URL = getIntent().getExtras().getString("url");
            VERSION_INFO = getIntent().getExtras().getString("version_info");
        } catch (Exception e) {
        }

        setTitleDisplay(false);
        initImage();

//        if (AppDesc.getText().toString().length() > 5) {
//            AppDesc.setTextSize(40f);
//        } else if (AppDesc.getText().toString().length() < 4) {
//            AppDesc.setTextSize(80f);
//        } else {
//            AppDesc.setTextSize(60f);
//        }

        setDownLoadReceiverHandle(new IDownLoadListener() {
            @Override
            public void DownloadStart(Context context, Intent intent, String url, String tag) {

                if (tag.equalsIgnoreCase(Tag)) {
                    textViewProgress.setText("0");
                    progress.setProgress(0.00f);
                    progress.start();
                    stepUploading();
                    LogUtils.e("DownloadStart");
                }
            }

            @Override
            public void DownloadLoading(Context context, Intent intent, String url, long total, long current, String tag) {
                if (tag.equalsIgnoreCase(Tag)) {
                    float val = (((current / 1F) / total));
                    textViewProgress.setText(((int) (val * 100)) + "");
                    progress.setProgress(val);
                    LogUtils.e("DownloadLoading:" + ((int) (val * 100)) + "");
                }

            }

            @Override
            public void DownloadFinish(Context context, Intent intent, String url, String filePath, String tag) {
                LogUtils.e("DownloadFinish");
                if (tag.equalsIgnoreCase(Tag)) {
                    try {
                        File file = new File(filePath);
                        if (file.exists() && !Check.isEmpty(filePath)) {
                            stepFinish();
                        } else {
                            ToastUtil.show(UploadApp.this, "更新失败");
                        }

                    } catch (Exception e) {
                        LogUtils.e(e.getMessage() + "");
                    }
                }
            }

            @Override
            public void DownloadCancelled(Context context, Intent intent, String url, String tag) {
                LogUtils.e("DownloadCancelled");
                if (tag.equalsIgnoreCase(Tag)) {

                }
            }

            @Override
            public void DownloadError(Context context, Intent intent, String url, String errorMsg, String tag) {
                LogUtils.e("DownloadError:" + errorMsg);
                if (tag.equalsIgnoreCase(Tag)) {

                }
            }
        });

        if (!Check.isEmpty(VERSION) && !Check.isEmpty(URL)) {
            path = AppApplication
                    .getAppDownLoadAppPath(UploadApp.this, URL);

            //直接更新
            download(Tag, URL, path);
            stepUploading();
        } else {
            stepInit();
            getData();
        }

    }

    void stepInit() {
        textViewCurrVerIsNew.setText("正在检查版本信息");
        linearLayoutVersion.setVisibility(View.VISIBLE);
        frameLayoutUploading.setVisibility(View.GONE);
        button.setVisibility(View.VISIBLE);
        button.setEnabled(false);
        button.setText("检查中...");
    }

    void stepHeightVersion() {
        textViewCurrVerIsNew.setText("已经是最新版本");
        String version = AndroidUtil.getVerName(this);
        textViewVer.setText(version);
        linearLayoutVersion.setVisibility(View.VISIBLE);
        frameLayoutUploading.setVisibility(View.GONE);
        button.setVisibility(View.VISIBLE);
    }

    void stepUploading() {
        linearLayoutVersion.setVisibility(View.GONE);
        frameLayoutUploading.setVisibility(View.VISIBLE);
        button.setVisibility(View.GONE);
    }

    void stepFinish() {
        textViewProgress.setText("100");
        linearLayoutVersion.setVisibility(View.GONE);
        frameLayoutUploading.setVisibility(View.VISIBLE);
        button.setText("点击更新");
        button.setVisibility(View.VISIBLE);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                installAPK();
            }
        });
        installAPK();
    }

    /**
     * 安装APK
     */
    void installAPK() {
        if (Build.VERSION.SDK_INT >= 26) { //判读版本是否在8.0以上 需要安装应用的权限
            boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            if (!haveInstallPermission) {
                new MaterialDialog.Builder(this)
                        .content("需要安装应用权限")
                        .positiveText("去设置")
                        .onPositive(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.cancel();
                                Uri packageURI = Uri.parse("package:" + getPackageName());
                                //注意这个是8.0新API
                                Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
                                startActivityForResult(intent, 10086);
                            }
                        })
                        .negativeText("取消")
                        .onNegative(new MaterialDialog.SingleButtonCallback() {
                            @Override
                            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                dialog.cancel();
                            }
                        })
                        .show();
                return;
            }
        }
        FileUtils.install(path, UploadApp.this);


    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 10086) {
            boolean haveInstallPermission = getPackageManager().canRequestPackageInstalls();
            if (haveInstallPermission) {
                FileUtils.install(path, UploadApp.this);
            }
        }
    }

    /**
     * http请求 检查更新版本信息
     */
    public static void CheckUpdate(final IReturnObject<String> function) {

        final String appName = AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppUniquenessName);
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("name", appName);
        KLog.e("appName:" + appName);
        HttpUtils http = new HttpUtils(UIApplication.NetWorkTimeOut);
        http.send(HttpMethod.GET, HttpUrlConstant.getWebSiteFullUrl(HttpUrlConstant.CheckVersion), params, new
                RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String result = responseInfo.result;
                        LogUtils.e("检测更新：" + result);
                        if (!Check.isEmpty(result)) {
                            if (function != null) {
                                function.returnResult(result);
                            }
                        } else {
                            if (function != null) {
                                function.returnResult(null);
                            }
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, String s) {
                        if (function != null) {
                            function.returnResult(null);
                        }
                    }
                });
    }

    /**
     * http请求 版本信息
     */
    void getData() {

        button.setEnabled(false);
        button.setText("检查中...");

        CheckUpdate(new IReturnObject<String>() {
            @Override
            public void returnResult(String result) {
                button.setEnabled(true);
                button.setText("检查更新");

                try {
                    if (result != null) {
                        JSONObject tempHeightVer = null;
                        final String IsDownloadUpdateTestApk = AppApplication.getAppKeyValueSet().readAppSetPreferences
                                (KeyConstant.IsDownloadUpdateTestApk);
                        final String appName = AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant
                                .AppUniquenessName);

                        JSONObject jsonObject = new JSONObject(result);
                        JSONObject appJson = jsonObject.getJSONObject(appName);
                        JSONArray Versions = appJson.getJSONArray("Versions");

                        for (int i = 0; i < Versions.length(); i++) {
                            JSONObject versionJson = Versions.getJSONObject(i);
                            if (!IsDownloadUpdateTestApk.equalsIgnoreCase("true") && versionJson.getString("Type").equalsIgnoreCase("T")) {
                                continue;
                            }
                            if (tempHeightVer == null) {
                                tempHeightVer = versionJson;
                            } else {
                                String oldVer = tempHeightVer.getString("Version");
                                String newVer = versionJson.getString("Version");

                                if (!Check.isEmpty(oldVer) && !Check.isEmpty(newVer)) {
                                    if (compareVersion(newVer, oldVer) == 1) {
                                        tempHeightVer = versionJson;
                                    }
                                }
                            }
                        }
                        String currVersion = AndroidUtil.getVerName(UploadApp.this);
                        if (compareVersion(tempHeightVer.getString("Version"), currVersion) == 1) {
                            //进行更新操作
                            final String url = tempHeightVer.getString("Url");
                            final String ver = tempHeightVer.getString("Version");
                            final String note = tempHeightVer.getString("Note");

                            textViewCurrVerIsNew.setText("发现新版本:" + ver);
                            linearLayoutVersion.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (TextUtils.isEmpty(note)) {
                                        return;
                                    }
                                    showSimpleDialogMessage(note, true);
                                }
                            });

                            button.setText("立即更新");
                            button.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    path = AppApplication
                                            .getAppDownLoadAppPath(UploadApp.this, url);
                                    download(Tag, url, path);
                                    stepUploading();
                                }
                            });

                        } else {
                            //提示已经是最新版本
                            stepHeightVersion();
                        }

                    } else {
                        KLog.e("检查更新失败");
                    }

                } catch (Exception e) {
                    KLog.e("检查更新失败" + e == null ? "null" : e.getMessage());
                }
            }
        });


    }

    /**
     * 比较版本号
     *
     * @param oldVer 格式 1.0.0.1
     * @param newVer 格式 2.0.0.1
     * @return
     */
    public static int compareVersion(String oldVer, String newVer) {
        int oldVerInt = Integer.parseInt(oldVer.replace(".", ""));
        int newVerInt = Integer.parseInt(newVer.replace(".", ""));

        try {
            String oldStr = "";
            String[] oldArray = oldVer.split("\\.");
            for (String item : oldArray) {
                if (item.length() == 1) {
                    item = "0" + item;
                }
                oldStr += item;
            }
            oldVerInt = Integer.parseInt(oldStr);
            //
            String newStr = "";
            String[] newArray = newVer.split("\\.");
            for (String item : newArray) {
                if (item.length() == 1) {
                    item = "0" + item;
                }
                newStr += item;
            }
            newVerInt = Integer.parseInt(newStr);
        } catch (Exception ex) {
            LogUtils.e("" + ex.getMessage());
        }

        if (oldVerInt > newVerInt) {
            return 1;
        } else if (newVer == oldVer) {
            return 0;
        } else {
            return -1;
        }
    }

    /**
     * 下载
     *
     * @param tag          可选的一个string类型参数,会和广播一起返回,一般根据它来判断正在更新的是哪一条数据
     * @param url
     * @param sd_file_name 要在sd卡上创建的完整文件名[包括文件夹+'/'+文件名]
     */
    public void download(String tag, String url, String sd_file_name) {

//        try {
//            File fileDir = new File(sd_file_name);
//            if (fileDir.exists()) {
//                fileDir.delete();
//                //FileUtils.cleanDirectory(fileDir);
//            }
////            MessageUtil.showShortToast(this, "删除历史升级APK,并且请求最新的更新APK文件");
//            LogUtils.d("删除历史升级APK,并且请求最新的更新APK文件");
//        } catch (Exception e) {
//            LogUtils.e(e.getMessage() + "");
//        }
        KLog.e(sd_file_name);

        final String Tag = tag;
        HttpUtils http = new HttpUtils();
        RequestParams params = new RequestParams();
        HttpHandler handler = http.download(url,
                sd_file_name,
                params,
                true, // 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
                false, // 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
                new RequestCallBack<File>() {

                    @Override
                    public void onStart() {
                        setRate(200);
                        LogUtils.d("开始下载:");
                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(DownloadStartReceiver.Action);
                        it.putExtra("url", getRequestUrl());
                        it.putExtra("tag", Tag);
                        sendBroadcast(it);
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        LogUtils.d("当前下载:" + current + "/" + total);

                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(DownloadLoadingReceiver.Action);
                        it.putExtra("url", getRequestUrl());
                        it.putExtra("tag", Tag);
                        it.putExtra("total", total);
                        it.putExtra("current", current);
                        sendBroadcast(it);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<File> responseInfo) {

                        LogUtils.d("下载成功:" + responseInfo.result.getPath());

                        Intent it = new Intent();// 创建Intent对象
                        it.setAction(DownloadFinishReceiver.Action);
                        it.putExtra("url", getRequestUrl());
                        it.putExtra("tag", Tag);
                        it.putExtra("filePath", URLDecoder.decode(responseInfo.result.getPath()));
                        sendBroadcast(it);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        KLog.e("下载错误:" + msg);
                        if (error != null && error.getExceptionCode() == 416) {
                            try {
                                File file = new File(path);
                                if (file.exists() && !Check.isEmpty(path)) {
                                    stepFinish();
                                } else {
                                    ToastUtil.show(UploadApp.this, "更新失败");
                                }

                            } catch (Exception e) {
                                LogUtils.e(e.getMessage() + "");
                            }
                        } else {
                            ToastUtil.show(UploadApp.this, "更新失败，服务器异常");
                            Intent it = new Intent();// 创建Intent对象
                            it.setAction(DownloadErrorReceiver.Action);
                            it.putExtra("url", getRequestUrl());
                            it.putExtra("tag", Tag);
                            it.putExtra("msg", msg);
                            sendBroadcast(it);
                        }

                    }
                });

        downloadList.put(tag, handler);
    }

    /**
     * 清除下载
     *
     * @param tag
     */
    public void cancelDownload(String tag) {
        HttpHandler httpHandler = downloadList.get(tag);
        if (httpHandler != null) {
            httpHandler.cancel();
            downloadList.remove(tag);
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        cancelDownload(Tag);
    }

    void initImage() {
        try {

//            AppDesc.setText(AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppDesc));

            String AppIconTitleVal = AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppIconTitle);
            String AppIconBackgroundVal = AppApplication.getAppKeyValueSet().readAppSetPreferences(KeyConstant.AppIconBackground);

            if (AppIconTitleVal.equalsIgnoreCase("app_icon_title.png")) {
                AppIconTitle.setImageBitmap(BitmapUtil.getRoundedCornerBitmap(BitmapFactory.decodeStream(this.getResources()
                        .openRawResource(R.raw.ic_launcher)), 15f));
            } else {
                getIconLoader().display(AppIconTitle, HttpUrlConstant.getWebSiteFullUrl(AppIconTitleVal));
            }
            if (AppIconBackgroundVal.equalsIgnoreCase("app_icon_background.png")) {
                AppIconBackground.setImageBitmap(BitmapFactory.decodeStream(this.getResources().openRawResource(R.raw
                        .app_icon_background)));
            } else {
                getIconLoader().display(AppIconBackground, HttpUrlConstant.getWebSiteFullUrl(AppIconBackgroundVal));
            }


        } catch (Exception e) {
            LogUtils.e(e.getMessage() + "");
        }
    }

}
